package com.config;

import com.Realm.UserRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @description:
 * @author: wu linchun
 * @time: 2021/4/5 10:59
 */
@Configuration
public class ShiroConfig {
    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
          /*
        anon:无需认证就可以访问
        authc:必须认证了才能访问
        user:必须拥有记住我功能才能使用
        perms:拥有对某个资源的权限才能访问
        role:拥有某个角色权限才能访问
         */
        //拦截
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/myc/myGrade", "authc");
        filterMap.put("/myc/gradeM", "perms[teacher]");  //perms[teacher]表示权限中必须有"teacher"这个字符串
        //filterMap.put("/myc/gradeM", "perms[admin]");
        bean.setFilterChainDefinitionMap(filterMap);
        //设置登录请求
        bean.setLoginUrl("/myc/tologin");   //没有登录的用户请求需要登录的页面时自动跳转到登录页面，filter里面需设置为“authc”
        //跳转至未授权页面
        bean.setUnauthorizedUrl("/myc/unauthorized");  //没有权限默认跳转的页面
        return bean;
    }

    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }

    //创建Realm对象，需自定义类
    @Bean(name = "userRealm")
    public UserRealm userRealm() {
        return new UserRealm();
    }
}
